import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:get/get.dart' hide MultipartFile hide FormData;
import 'package:video_compress/video_compress.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';

import 'logic.dart';
import 'state.dart';

class FollowUpEvaluationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FollowUpEvaluationPage();
  }
}

class _FollowUpEvaluationPage extends State<FollowUpEvaluationPage> {
  final FollowUpEvaluationLogic logic = Get.put(FollowUpEvaluationLogic());
  final FollowUpEvaluationState state =
      Get.find<FollowUpEvaluationLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: setWidth(1),
        backgroundColor: Colors.white,
        title: Text(
          '发表追评',
          style: TextStyle(
            color: Color(0xff030303),
            fontSize: 17,
          ),
        ),
        iconTheme: IconThemeData(
          color: Color(0xff030303),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              print('==== 提交 ==== 点击事件 ==== 事件 ====');
              logic.additionalComments();
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: setWidth(20)),
              alignment: Alignment.center,
              child: Text(
                '提交',
                style: TextStyle(
                  color: Color(0xffEA5504),
                  fontSize: 15,
                ),
              ),
            ),
          ),
        ],
      ),
      body: GetBuilder<FollowUpEvaluationLogic>(
        builder: (logic) {
          List<AssetEntity> imageList = state.imageList;
          List list = List.from(imageList);
          if (imageList.length < 9) {
            list.add('');
          }
          return Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(
                          left: setWidth(22),
                          top: setWidth(20),
                          right: setWidth(22),
                          bottom: setWidth(36),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            CachedImage(
                              width: setWidth(100),
                              height: setWidth(100),
                              margin: EdgeInsets.zero,
                              scale: BoxFit.fill,
                              path: state.goodsStr,
                            ),
                            SizedBox(
                              width: setWidth(18),
                            ),
                            Expanded(
                              child: Container(
                                height: setWidth(100),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      state.titleStr,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: Color(0xff222222),
                                        fontSize: 15,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Divider(
                        height: setWidth(1),
                        indent: setWidth(22),
                        endIndent: 0,
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: setWidth(18)),
                        child: Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: setWidth(22)),
                          child: TextField(
                            controller: state.textController,
                            style: TextStyle(
                              color: Color(0xff222222),
                              fontSize: 12,
                            ),
                            maxLines: 5,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.zero,
                              hintText: '针对本品发表一下您的看法和建议吧',
                              hintStyle: TextStyle(
                                color: Color(0xffcccccc),
                                fontSize: 12,
                              ),
                              enabledBorder: OutlineInputBorder(
                                // 设置输入框可编辑时的边框样式
                                borderRadius: BorderRadius.all(
                                    Radius.circular(0)), // 设置边框四个角的弧度
                                borderSide: BorderSide(
                                  // 用来配置边框的样式
                                  color: Colors.transparent, // 设置边框的颜色
                                  width: setWidth(1), // 设置边框的粗细
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                // 用来配置输入框获取焦点时的颜色
                                borderRadius: BorderRadius.all(
                                    Radius.circular(0)), // 设置边框四个角的弧度
                                borderSide: BorderSide(
                                  // 用来配置边框的样式
                                  color: Colors.transparent, // 设置边框的颜色
                                  width: setWidth(1), // 设置边框的粗细
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: setWidth(22)),
                        child: Wrap(
                          spacing: setWidth(24),
                          runSpacing: setWidth(20),
                          children: list
                              .asMap()
                              .map((key, value) {
                                if (imageList.length > key) {
                                  var asset = imageList[key];
                                  return MapEntry(
                                    key,
                                    Container(
                                      width: setWidth(120),
                                      height: setWidth(120),
                                      child: RepaintBoundary(
                                        child: ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(8.0),
                                          child: Stack(
                                            children: [
                                              Image(
                                                image: AssetEntityImageProvider(
                                                    imageList[key],
                                                    isOriginal: false),
                                                width: setWidth(120),
                                                height: setWidth(120),
                                                fit: BoxFit.cover,
                                              ),
                                              Visibility(
                                                  visible: asset.type ==
                                                      AssetType.video,
                                                  child: Positioned(
                                                      left: setWidth(30),
                                                      top: setWidth(30),
                                                      child: Icon(
                                                          Icons.play_circle,
                                                          size: setWidth(60))))
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                                }
                                return MapEntry(
                                  key,
                                  InkWell(
                                    onTap: () {
                                      print('！！！选择照片点击事件！！！ ');
                                      chooseSource(
                                        imagesAssetList: imageList,
                                      );
                                    },
                                    child: Container(
                                      width: setWidth(120),
                                      height: setWidth(120),
                                      alignment: Alignment.center,
                                      child: Image.asset(
                                        'assets/images/takingPictures_image.png',
                                        width: setWidth(120),
                                        height: setWidth(120),
                                        fit: BoxFit.fill,
                                      ),
                                    ),
                                  ),
                                );
                              })
                              .values
                              .toList(),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(30),
                      ),
                      // Divider(
                      //   height: setWidth(1),
                      //   indent: setWidth(22),
                      //   endIndent: 0,
                      // ),
                      // Container(
                      //   height: setWidth(68),
                      //   padding: EdgeInsets.symmetric(horizontal: setWidth(22)),
                      //   child: Row(
                      //     mainAxisAlignment: MainAxisAlignment.start,
                      //     crossAxisAlignment: CrossAxisAlignment.center,
                      //     children: [
                      //       Image.asset(
                      //         'assets/images/selectIcon1.png',
                      //         width: setWidth(34),
                      //         height: setWidth(34),
                      //         fit: BoxFit.cover,
                      //       ),
                      //       SizedBox(
                      //         width: setWidth(16),
                      //       ),
                      //       Text(
                      //         '匿名评价',
                      //         style: TextStyle(
                      //           color: Color(0xff333333),
                      //           fontSize: 12,
                      //         ),
                      //       ),
                      //     ],
                      //   ),
                      // ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  chooseSource({
    int index,
    List<AssetEntity> imagesAssetList,
  }) {
    showModalBottomSheet(
        isScrollControlled: true,
        builder: (BuildContext context) {
          //构建弹框中的内容
          return Container(
            color: Colors.white,
            height: setWidth(330) + Get.bottomBarHeight,
            margin: EdgeInsets.only(bottom: Get.bottomBarHeight),
            child: Column(
              children: ['照片', '视频', '取消']
                  .asMap()
                  .map((key, value) => MapEntry(
                      key,
                      Column(
                        children: [
                          InkWell(
                            onTap: () {
                              if (key != 2) {
                                choosePhoto(
                                  index: index,
                                  imagesAssetList: imagesAssetList,
                                  sourceType: key == 0
                                      ? RequestType.image
                                      : RequestType.video,
                                );
                              }
                              Get.back();
                            },
                            child: Container(
                              height: setWidth(100),
                              alignment: Alignment.center,
                              child: Text(value,
                                  style: TextStyle(
                                    color: Color(0xff222222),
                                    fontSize: setWidth(32),
                                  )),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: Color(0xffeeeeee),
                          )
                        ],
                      )))
                  .values
                  .toList(),
            ),
          );
        },
        context: context);
  }

  Future<void> choosePhoto({
    int index,
    List<AssetEntity> imagesAssetList,
    RequestType sourceType = RequestType.image,
  }) async {
    List<AssetEntity> asset = await AssetPicker.pickAssets(
      context,
      maxAssets: 9,
      selectedAssets: imagesAssetList,
      requestType: sourceType,
    );
    if (asset.length > 0) {
      state.imageList = asset;
      setState(() {});
    }
    if (asset.length == 0) return;

    upImageClick(imagesAssetList: asset, upIndex: 0);
  }

  // 上传图片
  void upImageClick({
    List<AssetEntity> imagesAssetList,
    int upIndex,
  }) async {
    var len = state.imageUrlList.length;
    AssetEntity upAsset = imagesAssetList[len];
    EasyLoading.show(
      status: "${len + 1}/${imagesAssetList.length} ",
      maskType: EasyLoadingMaskType.black,
    );
    File file = await upAsset.originFile;
    File compressedFile;
    if (upAsset.type == AssetType.video) {
      var info = await VideoCompress.compressVideo(
        file.path,
        quality: VideoQuality.LowQuality, // default(100)
      );
      compressedFile = info.file;
    } else {
      compressedFile = await FlutterNativeImage.compressImage(file.path,
          quality: 100, percentage: 40);
    }
    List<int> imageData = await compressedFile.readAsBytes();
    print('================ upAsset.name = ${upAsset.titleAsync}');
    String name = await upAsset.titleAsync;
    MultipartFile multipartFile = MultipartFile.fromBytes(
      imageData,
      filename: name,
    );
    Api.upImage(FormData.fromMap({"file": multipartFile})).listen((event) {
      if (event["code"] == 0) {
        var imageUrl = event["result"][0]["url"];
        print("====----=-==--=--=-=-=图片上传  upIndex===$len---$imageUrl");

        state.imageUrlList.add(imageUrl);
        EasyLoading.dismiss();
        logic.update();
        if ((imagesAssetList.length) > len + 1) {
          upImageClick(imagesAssetList: imagesAssetList, upIndex: upIndex + 1);
        } /*else {
          EasyLoading.dismiss();
          logic.update();
        }*/
      }
    }, onError: (error) {
      EasyLoading.dismiss();
      print(' 图片上传失败 error = $error');
    });
  }
}
